<?php
/**
 * 封装视图控制器
 * User: lisgroup
 * Date: 18-1-9
 * Time: 上午11:54
 */

namespace App;

use App\Utility\Storeroom;
use EasySwoole\Config;
use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Message\Status;
use EasySwoole\Core\Http\Request;
use EasySwoole\Core\Http\Response;
use think\Template;

abstract class ViewController extends Controller
{
    protected $view;
    protected $actionName;
    protected $request;
    protected $response;

    /**
     * 初始化模板引擎
     * ViewController constructor.
     * @param string $actionName
     * @param Request $request
     * @param Response $response
     */
    function __construct(string $actionName, Request $request, Response $response)
    {
        $this->view = new Template();
        $this->request = $request;
        $this->response = $response;
        $this->actionName = $actionName;

        if ($actionName == '__construct') {
            $this->response()->withStatus(Status::CODE_BAD_REQUEST);
        } else {
            Storeroom::instance()->item('view', $this->view);
            Storeroom::instance()->item('request', $this->request);
            Storeroom::instance()->item('response', $this->response);
        }

        $tempPath = Config::getInstance()->getConf('TEMP_DIR');// 临时文件目录
        //$tempPath = Di::getInstance()->get('TEMP_DIR');     // 导致模板错误 error
        $this->view->config([
            'view_path' => EASYSWOOLE_ROOT.'/Application/view/',              // 模板文件目录
            'cache_path' => "{$tempPath}/templates_c/",               // 模板编译目录
        ]);

        parent::__construct($actionName, $request, $response);
    }

    /**
     * 输出模板到页面
     * @param  string|null $template 模板文件
     * @param array $vars 模板变量值
     * @param array $config 额外的渲染配置
     * @author : evalor <master@evalor.cn>
     */
    function fetch($template, $vars = [], $config = [])
    {
        ob_start();
        $this->view->fetch($template, $vars, $config);
        $content = ob_get_clean();
        $this->response()->write($content);
    }

    protected function request(): Request
    {
        //return $this->request;
        return Storeroom::instance()->item('request');
    }

    protected function response(): Response
    {
        //return $this->response;
        return Storeroom::instance()->item('response');
    }
}
